package com.oraro.paygatewaybiz.channel.alipay.tradetype.webnative;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.oraro.common.result.Result;
import com.oraro.middleservice.logger.starter.supports.BizLoggerHelper;
import com.oraro.paygatewaybiz.channel.alipay.interfaces.AliPayService;
import com.oraro.paygatewaybiz.channel.alipay.serviceImpl.AbstractAliBaseService;
import com.oraro.paygatewaybiz.constant.Constants;
import com.oraro.paygatewaybiz.exception.RRException;
import com.oraro.paygatewaybiz.module.entity.ChannelEntity;
import com.oraro.paygatewaybiz.module.entity.OrderEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;

/**
 * @Author: jianghuiyong
 * @Date: 2018/12/10 10:46
 * @Version 1.0
 */
@Slf4j
@Service
public class AlipayNativeService extends AbstractAliBaseService implements AliPayService {

    @Autowired
    private BizLoggerHelper bizLoggerHelper;

    @Override
    public String type() {
        return Constants.tradeType.ALINATIVE.getType();
    }

    @Override
    public Result payOrder(OrderEntity orderEntity, ChannelEntity channelEntity) {

        AlipayTradePagePayRequest alipayTradePagePayRequest;
        try {
            alipayTradePagePayRequest = getNativeReqParams(orderEntity, channelEntity.getReturnUrl());
        } catch (UnsupportedEncodingException e) {
            throw new RRException("支付宝下单失败");
        }
        //实例化客户端
        AlipayClient alipayClient = getInstance(channelEntity.getAppId(), channelEntity.getMerchantPrivateKey(), channelEntity.getAlipayPublicKey());
        String result = "";
        try {
            result = alipayClient.pageExecute(alipayTradePagePayRequest).getBody();
        } catch (AlipayApiException e) {
            throw new RRException("支付宝下单失败");
        }
        bizLoggerHelper.log("支付宝下单返回参数:"+ result);
        return Result.success().data("result", result);
    }
}
